package com.emmmya.ocs.common.utils;

import com.emmmya.ocs.common.constant.RedisConstant;
import com.emmmya.ocs.config.redis.RedisManager;
import com.emmmya.ocs.config.security.jwt.JwtConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @description:
 * @author: 咕噜肉IT小店-黑医
 * @createDate: 2020-05-14
 * @version: 1.0
 */
@Slf4j
@Component
public class JwtUtils {
    @Autowired
    JwtConfig jwtConfig;
    @Autowired
    RedisManager redisManager;
    /**
     * 判断token是否已经过期,先解析token的数值，判断token中的过期时间。最后同token获取username，
     * 根据username来获取redis缓存动中的token如果存在，并且与传来的值相同，则说明token没有过期。返回false;
     * @param token
     * @return      true过期，false没有过期
     */
    public Boolean isOver(String token){
        Date expirationDateFromToken = jwtConfig.getExpirationDateFromToken(token);
        boolean tokenExpired = jwtConfig.isTokenExpired(expirationDateFromToken);
        //如果没有过期，则查询redis
        if(!tokenExpired){
            String rtoken = (String) redisManager.get(RedisConstant.REDIS_USER_TOKEN + getUsername(token));
            if(token.equals(rtoken)){
                return false;
            }
        }
        return true;
    }

    /**
     * 获取token的username
     */
    public String getUsername(String token){
        return jwtConfig.getUsernameFromToken(token);
    }

    /**
     *
     */
    public boolean verify(String token,String username){
        return jwtConfig.verify(token,username);
    }
}
